<template>
	<div class="home-container">
		<!-- 顶部欢迎区域 -->
		<div class="container-top">
			<TopWelcome :loginName="userInfo.userName" :groupName="userInfo.omDepts?.pollutionSourceName">
				<!-- 通知公告滚动条 -->
				<template #notice>
					<div class="notice" v-if="noticeTop">
						<van-notice-bar :text="noticeTop" left-icon="volume-o" color="#FFF8E7" background="transparent" @click="gotoNoticeDetail" />
					</div>
				</template>
			</TopWelcome>
		</div>

		<!-- 功能菜单区域 -->
		<div class="all-menu-contain">
			<div class="all-menu">
				<div v-for="(item, index) in menulistBuyPower" :key="index" class="menu-box" @click="onClickMenu(item)">
					<!-- 红点角标 -->
					<div v-if="getBadgeCount(item.name) > 0" class="item-info-rwsl">
						{{ getBadgeCount(item.name) }}
					</div>

					<div class="menu-box-item">
						<div class="menu-icon" :class="item.iconClass"></div>
						<div>{{ item.name }}</div>
					</div>
				</div>
			</div>
		</div>

		<!-- 绑定弹窗 -->
		<PopupBound :show="showPopup" @close="closeShowPopup" />

		<!-- 登录状态提示 -->
		<LoginStatus
			:statusCode="loginStatusCode"
			:statusMessage="loginStatusMessage"
			:show="showLoginStatus"
			@close="closeLoginStatus"
			@refresh="handleLoginStatusRefresh"
		/>
	</div>
</template>

<script>
import { ref, computed, onMounted, onActivated, watch, nextTick } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import { useUserStore, useCacheStore } from '../../stores'
import { useOAuthLogin } from '@/utils/oauthHandler'
import { useOAuthState } from '@/utils/oauthState'
import * as homeApi from '../../api/home'
import * as userApi from '../../api/user'
import { locationPollution } from '../../api/index'
import { encode as base64Encode } from '../../utils/base64'
import TopWelcome from './components/TopWelcome.vue'
import PopupBound from './components/PopupBound.vue'
import LoginStatus from '../../components/LoginStatus.vue'
import { ROLES_MENU } from './constants'
import { showToast } from 'vant'

export default {
	name: 'Home',
	components: {
		TopWelcome,
		PopupBound,
		LoginStatus,
	},
	setup() {
		const router = useRouter()
		const route = useRoute()
		const userStore = useUserStore()
		const cacheStore = useCacheStore()

		// OAuth 登录工具
		const { handleLogin, redirectToAuth } = useOAuthLogin()
		const { setAuthState } = useOAuthState()
		const isAuthenticating = ref(false)
		const isAuthReady = ref(false)

		const showPopup = ref(false)
		const userInfo = ref({})
		const menulistBuyPower = ref([])
		const noticeTop = ref('')
		const undoneCount = ref(0)
		const noReadCount = ref(0)
		const questionnaireCount = ref(0)
		const loginStatusCode = ref('') // 登录状态码
		const loginStatusMessage = ref('') // 登录状态消息
		const showLoginStatus = ref(false) // 是否显示登录状态弹窗

		// 获取角标数量
		const getBadgeCount = (menuName) => {
			switch (menuName) {
				case '通知公告':
					return noReadCount.value
				case '问题整改':
					return undoneCount.value
				case '问卷调查':
					return questionnaireCount.value
				default:
					return 0
			}
		}

		// 简化的首页级别 OAuth 初始化（迁移自 App.vue）
		const initializeAuth = async () => {
			try {
				isAuthenticating.value = true
				userStore.loadFromCache()
				const urlParams = new URLSearchParams(window.location.search)
				let code = urlParams.get('code')
				const openid = urlParams.get('openid')
				if (!code) {
					code = userStore.code
					console.log('从 userStore 获取 code:', userStore.code)
				}

				if (code || openid) {
					setAuthState('authenticating')
					const result = await handleLogin()
					if (result.success) {
						setAuthState('success')
						isAuthReady.value = true
					} else if (result.needSpecialHandle && result.code) {
						// 特殊状态码（50001/50002/50003）由首页弹窗处理
						setAuthState('success')
						// 将状态保存在 userStore，供 initData 判定
						userStore.specialAuthCode = result.code
						userStore.specialAuthMsg = result.msg
						isAuthReady.value = true
					} else {
						setAuthState('failed', new Error(result.error))
						setTimeout(async () => {
							await redirectToAuth()
						}, 1200)
					}
				} else {
					if (userStore.isAuthenticated) {
						setAuthState('success')
						isAuthReady.value = true
					} else {
						setAuthState('authenticating')
						await redirectToAuth()
					}
				}
			} catch (e) {
				console.error('首页 OAuth 初始化失败:', e)
				setTimeout(async () => {
					try {
						await redirectToAuth()
					} catch (inner) {
						console.error('跳转授权失败:', inner)
					}
				}, 800)
			} finally {
				isAuthenticating.value = false
			}
		}

		// 初始化数据
		const initData = async () => {
			try {
				console.log('开始初始化首页数据...')

				// 检查用户登录状态和状态码
				let statusCode = ''
				let loginRes = null
				let statusMessage = ''

				// 读取在 initializeAuth 中临时保存的特殊状态码
				if (userStore.specialAuthCode) {
					statusCode = userStore.specialAuthCode
					loginStatusCode.value = statusCode
					loginRes = userStore.userInfo || {}
					console.log('读取特殊认证状态码:', statusCode)
					// 清除一次性标记
					userStore.specialAuthCode = ''
					statusMessage = userStore.specialAuthMsg || ''
					loginStatusMessage.value = statusMessage
				}

				// 如果从缓存读取到了状态码，跳过登录直接处理状态
				console.log('当前状态码:', statusCode)
				if (!statusCode) {
					// 优先检查是否已经认证（有token），这样可以避免重复登录
					if (userStore.isAuthenticated && userStore.userInfo) {
						// 已经有token和用户信息，直接使用
						console.log('✅ 用户已认证，使用已有token和用户信息加载数据')
						loginRes = userStore.userInfo
						console.log('📊 用户信息:', loginRes)
					} else if (userStore.isCodeValid) {
						// 有有效的code，尝试登录
						console.log('🔄 使用code重新登录...')
						const result = await userStore.loginWithCode(userStore.code)
						console.log('登录结果:', result)

						if (result.success) {
							// 登录成功，有token
							loginRes = result.data
							console.log('✅ 登录成功，用户数据:', loginRes)
						} else if (['50001', '50002', '50003'].includes(result.code)) {
							// 特殊状态码（未绑定/待审核/审核未通过）
							statusCode = result.code
							loginStatusCode.value = statusCode
							loginStatusMessage.value = result.msg || ''
							console.log('读取登录返回的特殊状态码:', statusCode)
							console.log('读取登录返回的特殊状态消息:', loginStatusMessage)
							loginRes = result.data || userStore.userInfo
							console.log('⚠️  登录返回特殊状态码:', statusCode, '用户数据:', loginRes)
						} else {
							// 登录失败
							console.error('❌ 登录失败:', result)
						}
					} else if (userStore.isAuthenticated) {
						// 有token但没有用户信息，尝试确保登录
						console.log('🔄 用户已认证但缺少用户信息，尝试ensureLogin...')
						try {
							loginRes = await userStore.ensureLogin()
							console.log('✅ ensureLogin成功，用户数据:', loginRes)
						} catch (error) {
							console.error('❌ 使用token登录失败', error)
						}
					} else {
						// 没有code也没有token，等待OAuth登录
						console.log('⏳ 用户未认证，显示默认菜单，等待OAuth登录完成...')
						menulistBuyPower.value = ROLES_MENU.unbound
						userInfo.value = {}
						return
					}
				}

				// 如果是未绑定状态（50001），只显示绑定企业和法律法规菜单
				// 此时用户已通过OAuth认证，但未绑定企业，只能访问：
				// 1. 绑定企业功能（完成绑定）
				// 2. 法律法规功能（公开访问，无需登录）
				if (statusCode === '50001') {
					console.log('🎯 用户未绑定企业，显示未绑定菜单和提示弹窗')
					console.log('📋 设置菜单为 ROLES_MENU.unbound')
					menulistBuyPower.value = ROLES_MENU.unbound
					userInfo.value = loginRes || {}

					// 显示登录状态提示
					console.log('🔧 设置弹窗参数...')
					loginStatusCode.value = statusCode
					//	loginStatusMessage.value = '您尚未进行实名制认证，请先完成企业绑定'

					// 使用 nextTick 确保组件已挂载后再显示弹窗
					await nextTick()
					showLoginStatus.value = true

					// 不获取统计数据和通知（这些需要完成企业绑定后才能访问）
					return
				}

				// 如果是其他特殊状态（50002、50003），显示默认菜单和提示
				if (statusCode === '50002' || statusCode === '50003') {
					menulistBuyPower.value = ROLES_MENU.unbound
					userInfo.value = loginRes || {}
					// 显示登录状态提示
					loginStatusCode.value = statusCode
					if (statusCode === '50002') {
						//loginStatusMessage.value = '您的实名制认证正在审核中，请耐心等待'
					} else if (statusCode === '50003') {
						//loginStatusMessage.value = '您的实名制认证未通过审核，请联系管理员'
					}
					//替换字符串' 实名审核未通过：'
					// loginStatusMessage.value = loginStatusMessage.value.replace('实名审核未通过：', '')
					console.log('🔧 设置弹窗参数...')
					console.log('📊 loginStatusCode.value =', loginStatusCode.value)
					console.log('📊 loginStatusMessage.value =', loginStatusMessage.value)

					// 使用 nextTick 确保组件已挂载后再显示弹窗
					await nextTick()
					showLoginStatus.value = true
					console.log('✅ 已设置 showLoginStatus = true, 状态码:', statusCode)

					return
				}

				// 正常登录状态，显示完整菜单
				if (!loginRes) {
					console.error('没有获取到用户数据')
					menulistBuyPower.value = ROLES_MENU.enterprise.defaut
					userInfo.value = {}
					return
				}

				console.log('用户正常登录，加载完整菜单，用户数据:', loginRes)

				const menuGov = await roleMenus(loginRes)
				menulistBuyPower.value = menuGov
				userInfo.value = loginRes

				// 获取首页统计数据
				getHomeCount()
				queryNoticeList()
			} catch (e) {
				console.error('初始化数据失败', e)
				// 显示默认菜单
				const menuGov = ROLES_MENU.enterprise.defaut
				menulistBuyPower.value = menuGov
				userInfo.value = {}
			}
			console.log(userInfo)
		}

		// 根据用户角色获取菜单
		const roleMenus = async (user) => {
			let menuGov = []

			if (user.userRoles !== 'government') {
				if (user.isEnterpriseTown) {
					menuGov = ROLES_MENU.enterprise.district
				} else {
					menuGov = ROLES_MENU.enterprise.defaut
				}

				try {
					const pollutionRes = await locationPollution()
					if (pollutionRes.code === '0') {
						const pollutionInfo = pollutionRes.data
						user.omDepts = pollutionInfo
						cacheStore.setCachedData('userInfo', user)

						// 根据企业污染源信息动态调整菜单
						menuGov = menuGov.map((item) => {
							// 处理自查自纠菜单（id为2）
							if (item.id === '2' && pollutionInfo.existSzesisc === '1') {
								// 修改菜单名称和图标为"苏州自查自纠"
								item.iconClass = 'icon-12'
								item.name = '苏州自查自纠'

								// 根据existWateReuse判断跳转目标
								// 跳转到苏州第三方H5页面，需要base64编码参数
								// 与小程序保持一致的编码方式
								const mobile = base64Encode(user.phonenumber || '')
								const userName = base64Encode(user.userName || '')
								const creditCode = base64Encode(pollutionInfo.creditCode || '')

								const externalUrl = `https://szesisc.sthjj.suzhou.com.cn?mobile=${mobile}&userName=${userName}&creditCode=${creditCode}`

								console.log('构建苏州自查自纠外部链接:', {
									mobile: user.phonenumber,
									userName: user.userName,
									creditCode: pollutionInfo.creditCode,
									url: externalUrl,
								})

								// 标记为外部链接
								item.isExternal = true
								item.externalUrl = externalUrl
								item.router = externalUrl // 保留router用于兼容
							} else {
								// 跳转到内部设施检查页面
								item.isExternal = false
							}
							return item
						})
					}
				} catch (error) {
					console.error('获取污染源信息失败', error)
				}
			} else {
				menuGov = ROLES_MENU.government.getMenuByRoles(user.pcRoles)
			}

			return menuGov
		}

		// 获取首页统计数据
		const getHomeCount = async () => {
			try {
				const [undoneRes, noReadRes, questionnaireRes] = await Promise.all([
					homeApi.getUndoneCount({}),
					homeApi.getNoReadCount({}),
					homeApi.questionnaireCount(),
				])

				// 根据小程序的响应格式处理数据
				undoneCount.value = undoneRes.code === '0' ? undoneRes.data || 0 : 0
				noReadCount.value = noReadRes.code === '0' ? noReadRes.data || 0 : 0
				questionnaireCount.value = questionnaireRes.code === '0' ? questionnaireRes.data || 0 : 0
			} catch (error) {
				console.error('获取统计数据失败', error)
				// 使用模拟数据
				undoneCount.value = 0
				noReadCount.value = 17
				questionnaireCount.value = 0
			}
		}

		// 获取通知列表
		const queryNoticeList = async () => {
			try {
				const res = await homeApi.queryNoticeList({
					pageNum: 1,
					pageSize: 1,
				})

				if (res.code === '0' && res.rows && res.rows.length > 0) {
					let text = res.rows[0].noticeTitle
					text = text.replace(/<[^<>]+>/g, '').replace(/&nbsp;/gi, '')
					noticeTop.value = text
					cacheStore.setCachedData('noticeList', res.rows)
				}
			} catch (error) {
				console.error('获取通知列表失败', error)
				// 使用模拟数据
				noticeTop.value = '关于加强台风防范工作的提示'
			}
		}

		// 点击菜单项
		const onClickMenu = (item) => {
			if (!item.router) {
				showToast('系统功能建设中')
				return
			}

			console.log('点击菜单:', item)

			// 判断是否为外部链接
			if (item.isExternal && item.externalUrl) {
				// 跳转到外部H5页面
				console.log('跳转到外部链接:', item.externalUrl)
				window.location.href = item.externalUrl
				return
			}

			// 根据路由进行页面跳转
			router.push(item.router)
		}

		// 跳转到通知详情
		const gotoNoticeDetail = () => {
			// 获取缓存的通知列表
			const noticeList = cacheStore.getCachedData('noticeList')
			console.log('noticeList', noticeList)

			// noticeList 的结构是 { data: Array, timestamp: number, expireTime: number }
			if (noticeList && noticeList.data && noticeList.data.length > 0) {
				// 获取第一条通知
				const firstNotice = noticeList.data[0]

				// 直接跳转到详情页
				router.push({
					path: '/notice/detail',
					query: {
						id: firstNotice.noticeId,
					},
				})
			} else {
				// 如果没有通知数据，跳转到通知列表页
				router.push('/notice/list')
			}
		}

		// 关闭弹窗
		const closeShowPopup = () => {
			showPopup.value = false
		}

		// 关闭登录状态弹窗
		const closeLoginStatus = () => {
			showLoginStatus.value = false
		}

		onMounted(() => {
			console.log('首页onMounted，开始OAuth初始化')
			initializeAuth().then(() => {
				// 认证准备好后再加载首页业务数据，避免等待轮询
				if (isAuthReady.value) {
					initData()
				}
			})
		})

		// 页面激活时重新加载（从其他页面返回时）
		// 主要用于从绑定页面返回后刷新数据，或审核通过后重新进入首页
		onActivated(() => {
			console.log('首页onActivated，检查是否需要刷新数据')
			// 如果用户已登录且有token，重新加载数据
			if (userStore.isAuthenticated) {
				console.log('✅ 用户已登录，重新加载首页数据')
				// 清除之前的状态码，重新检测
				loginStatusCode.value = ''
				loginStatusMessage.value = ''
				showLoginStatus.value = false
				initData()
			} else if (userStore.isCodeValid) {
				// 如果有有效的code，也尝试刷新（可能是审核通过后）
				console.log('🔄 检测到有效code，尝试刷新登录状态')
				loginStatusCode.value = ''
				loginStatusMessage.value = ''
				showLoginStatus.value = false
				initData()
			}
		})

		const handleLoginStatusRefresh = async () => {
			console.log('处理登录状态刷新请求...')
			// 关闭弹窗
			showLoginStatus.value = false
			// 重新初始化数据
			await initData()
		}

		return {
			showPopup,
			userInfo,
			menulistBuyPower,
			noticeTop,
			getBadgeCount,
			onClickMenu,
			gotoNoticeDetail,
			closeShowPopup,
			loginStatusCode,
			loginStatusMessage,
			showLoginStatus,
			closeLoginStatus,
			handleLoginStatusRefresh,
		}
	},
}
</script>

<style lang="less" scoped>
.home-container {
	background-color: #f7f7f7;
	min-height: 100vh;
	padding-bottom: 60px;
}

.container-top {
	background-color: #fff;
	border-radius: 0 0 10px 10px;
	position: relative;
}

.company-info-card {
	margin: 0 16px;
	padding: 16px;
	background: rgba(255, 255, 255, 0.1);
	border-radius: 8px;
	backdrop-filter: blur(10px);
	margin-top: 16px;

	.company-name {
		color: #333;
		font-size: 16px;
		font-weight: 500;
	}
}

.all-menu-contain {
	background-color: #fff;
	border-radius: 10px;
	padding: 20px 0 0 0;
	margin: 10px 16px 60px 16px;
}

.all-menu {
	display: grid;
	grid-template-columns: 1fr 1fr;
	justify-content: center;
	grid-column-gap: 16px;
	grid-row-gap: 16px;
	padding: 0 16px 20px;
}

.menu-box {
	position: relative;
	height: 100px;
	display: flex;
	align-items: center;
	background: #f8f8f8;
	color: #202739;
	font-size: 14px;
	font-weight: 600;
	border-radius: 10px;
	cursor: pointer;
	transition: all 0.3s ease;

	&:active {
		transform: scale(0.98);
		background: #f0f0f0;
	}
}

.menu-box-item {
	margin: 0 auto;
	text-align: center;
}

.menu-icon {
	width: 40px;
	height: 38px;
	margin: 0 auto 10px auto;
	background-size: 100%;

	&.icon-0 {
		background-image: url('https://wx.ksepia.com/profile/mini-image/icon-0x3.png');
	}
	&.icon-2 {
		background-image: url('https://wx.ksepia.com/profile/mini-image/icon-2x3.png');
	}
	&.icon-5 {
		background-image: url('https://wx.ksepia.com/profile/mini-image/icon-5x3.png');
	}
	&.icon-6 {
		background-image: url('https://wx.ksepia.com/profile/mini-image/icon-6@3x.png');
	}
	&.icon-7 {
		background-image: url('https://wx.ksepia.com/profile/mini-image/icon-7@3x.png');
	}
	&.icon-9 {
		background-image: url('https://wx.ksepia.com/profile/mini-image/icon-5x3.png');
	}
	&.icon-11 {
		background-image: url('https://wx.ksepia.com/profile/mini-image/icon-11.png');
	}
	&.icon-12 {
		background-image: url('https://wx.ksepia.com/profile/mini-image/icon-12.png');
	}
	&.icon-13 {
		background-image: url('https://wx.ksepia.com/profile/mini-image/icon-13.png');
	}
	.icon-14 {
		background-image: url('https://wx.ksepia.com/profile/mini-image/low-x3.png');
	}
}

.item-info-rwsl {
	position: absolute;
	top: 10px;
	right: 10px;
	min-width: 16px;
	display: inline-block;
	padding: 0 3px;
	color: #fff;
	font-weight: 500;
	font-size: 12px;
	line-height: 1.2;
	text-align: center;
	background-color: #ee0a24;
	border: 1px solid #fff;
	border-radius: 16px;
	transform: translate(40%, -40%);
	transform-origin: 100%;
}
</style>
